package com.simple.crawler.core.listener;

import com.simple.crawler.aop.AopHelper;
import com.simple.crawler.aop.Listener;
import com.simple.crawler.constant.CrawlerEngineStatus;
import com.simple.crawler.constant.CrawlerStatus;
import com.simple.crawler.core.Crawler;
import com.simple.crawler.core.CrawlerContext;
import com.simple.crawler.core.Task;
import com.simple.crawler.core.TaskExecutor;
import com.simple.crawler.utils.ReflectUtils;
import com.simple.crawler.utils.StringUtils;
import net.sf.cglib.proxy.MethodProxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class CrawlerEngineActuator implements Listener {

    private CrawlerEngineStatus status = CrawlerEngineStatus.READY;

    @Override
    public boolean filter(String method) {
        return StringUtils.isContains("deploy,start,pause,stop", method);
    }

    @Override
    public void after(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Exception {
        /*if (!"deploy".equals(method.getName()) && !CrawlerEngineStatus.RUNNING.equals(status)) {
            return;
        }*/
        ReflectUtils.invoke(this, method.getName(), objects, Void.class);
    }

    private void deploy(String pkg) {
        if (StringUtils.isBlank(pkg)) {
            return;
        }
        ReflectUtils.getClassList(pkg, Crawler.class).stream().map(c -> AopHelper.getAopHelper().initObj(c)).forEach(obj -> CrawlerContext.addCrawler(obj));
        status = CrawlerEngineStatus.RUNNING;
    }

    public void deploy(String url, Class<? extends Task>... taskList) {
        Crawler crawler = ReflectUtils.getInstance(Crawler.class, url, taskList);
        if (crawler == null) {
            return;
        }
        CrawlerContext.addCrawler(crawler);
    }

    private void start() {
        Collection<Crawler> crawlerMap = CrawlerContext.getCrawler().values();
        if (crawlerMap.isEmpty()) {
            return;
        }
        crawlerMap.stream().filter(crawler -> crawler.isValidate()).forEach(crawler -> {
            Object[] args = new Object[]{crawler.getId(), 0, crawler.getUrl()};
            Task task = AopHelper.getAopHelper().initObj(crawler.getTaskList()[0], args);
            if (task == null) {
                return;
            }
            TaskExecutor.addTask(task);
        });
    }

    private void pause() {

    }

    private  void stop() {

    }

}
